<template>
	<view class="info">
		<view style="margin-top: 100px;">连接状态: {{ connectionStatus }}</view>
		<view style="margin: 20rpx 0;">调试信息：{{ debugInfo }}</view>
		<view style="margin: 20rpx 0;">收到的消息：{{ receivedMessage }}</view>
		
		<button @tap="connectWebSocket" :disabled="isConnecting">连接 WebSocket</button>
		<button @tap="sendUploadMessage" :disabled="!socketOpen" style="margin-top: 20rpx; background: #4CAF50;">
			发送上传消息
		</button>
		<button @tap="disconnect" :disabled="!socketOpen" style="margin-top: 20rpx; background: #FF9800;">
			断开连接
		</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				connectionStatus: '未连接',
				debugInfo: '准备连接...',
				receivedMessage: '',
				isConnecting: false,
				socketOpen: false,
				socketTask: null,
				sessionId: this.generateSessionId() // 生成测试 sessionId
			}
		},

		onLoad() {
			this.debugInfo = `SessionId: ${this.sessionId}`
		},

		onUnload() {
			this.closeSocket()
		},

		methods: {
			// 生成随机 sessionId 用于测试
			generateSessionId() {
				return '11' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
			},

			// 构建完整的 WebSocket URL
			buildWebSocketUrl() {
				const baseUrl = 'ws://192.168.2.157:8088'
				const path = '/ws/upload'
				const params = `?type=user&sessionId=${this.sessionId}`
				
				return baseUrl + path + params
			},

			// 连接 WebSocket
			connectWebSocket() {
				this.isConnecting = true
				this.connectionStatus = '连接中...'
				
				// 关闭现有连接
				this.closeSocket()
				
				const url = this.buildWebSocketUrl()
				this.debugInfo = `连接URL: ${url}`
				console.log('🔄 连接 WebSocket:', url)
				
				this.socketTask = uni.connectSocket({
					url: url,
					// 对于带参数的 WebSocket，可能需要这些 header
					header: {
						'content-type': 'application/json',
						'Authorization': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJDTEFJTV9OQU1FX1VTRVJDT0RFIjoiYWRtaW4iLCJDTEFJTV9OQU1FX1VTRVJJRCI6MSwiQ0xBSU1fTkFNRV9ST0xFSUQiOjEsIkNMQUlNX05BTUVfVVNFUk5BTUUiOiJhZG1pbiIsImV4cCI6MTc2Mjc1NjkxMCwiQ0xBSU1fTkFNRV9MT0dJTlRZUEUiOjAsImlhdCI6MTc2Mjc1NjkwMn0.aVJeTdoUtANClO27LoYqSHNywIQl5AX-9VxCSkdQgCQ' // 如果需要认证
					},
					success: () => {
						console.log('✅ connectSocket 调用成功')
					},
					fail: (err) => {
						console.error('❌ connectSocket 调用失败:', err)
						this.isConnecting = false
						this.connectionStatus = '连接失败'
						this.debugInfo = `连接失败: ${err.errMsg}`
						this.showError('WebSocket 连接失败')
					}
				})
				
				// 设置监听器
				this.setupSocketListeners()
			},

			// 设置 WebSocket 监听器
			setupSocketListeners() {
				if (!this.socketTask) return
				
				// 连接打开
				this.socketTask.onOpen((res) => {
					console.log('✅ WebSocket 连接已打开', res)
					this.isConnecting = false
					this.socketOpen = true
					this.connectionStatus = '已连接'
					this.debugInfo = 'WebSocket 连接成功！'
					this.receivedMessage = '连接建立，可以发送消息了'
					
					// 连接成功后发送认证消息（如果需要）
					this.sendAuthMessage()
				})
				
				// 接收消息
				this.socketTask.onMessage((res) => {
					console.log('📩 收到服务器消息:', res)
					try {
						const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data
						this.receivedMessage = JSON.stringify(data, null, 2)
						this.debugInfo = `收到消息: ${new Date().toLocaleTimeString()}`
					} catch (e) {
						this.receivedMessage = res.data
						this.debugInfo = `收到文本消息: ${new Date().toLocaleTimeString()}`
					}
				})
				
				// 连接关闭
				this.socketTask.onClose((res) => {
					console.log('⚠ WebSocket 连接关闭:', res)
					this.isConnecting = false
					this.socketOpen = false
					this.connectionStatus = '连接已关闭'
					this.debugInfo = `连接关闭: ${res.code} - ${res.reason || '未知原因'}`
					
					// 如果不是正常关闭，尝试重连
					if (res.code !== 1000) {
						setTimeout(() => {
							this.connectWebSocket()
						}, 3000)
					}
				})
				
				// 连接错误
				this.socketTask.onError((err) => {
					console.error('❌ WebSocket 错误:', err)
					this.isConnecting = false
					this.socketOpen = false
					this.connectionStatus = '连接错误'
					this.debugInfo = `连接错误: ${err.errMsg || '未知错误'}`
				})
			},
			// 发送认证消息（如果需要）
			sendAuthMessage() {
				const authMsg = {
					type: 'auth',
					// role: 'user',
					sessionId: this.sessionId,
					timestamp: new Date().toISOString()
				}
				this.sendSocketMessage(authMsg)
			},
			// 发送图片上传消息
			sendUploadMessage() {
				const uploadMsg = {
					type: 'image_upload',
					userId: 1,
					sessionId: this.sessionId,
					fileName: 'test_image.jpg',
					fileSize: '2MB',
					imageData: [
						'https://example.com/image1.jpg',
						'https://example.com/image2.jpg'
					],
					timestamp: new Date().toISOString(),
				}
				
				this.sendSocketMessage(uploadMsg)
			},

			// 通用消息发送方法
			sendSocketMessage(message) {
				if (!this.socketOpen || !this.socketTask) {
					this.showError('WebSocket 未连接')
					return
				}
				
				console.log('📤 发送消息:', message)
				
				this.socketTask.send({
					data: JSON.stringify(message),
					success: () => {
						console.log('✅ 消息发送成功')
						this.debugInfo = `消息发送成功: ${message.type}`
						uni.showToast({
							title: '发送成功',
							icon: 'success'
						})
					},
					fail: (err) => {
						console.error('❌ 消息发送失败:', err)
						this.debugInfo = `发送失败: ${err.errMsg}`
						this.showError('消息发送失败')
					}
				})
			},

			// 断开连接
			disconnect() {
				this.closeSocket()
				this.connectionStatus = '已断开'
				this.debugInfo = '连接已手动断开'
				this.receivedMessage = ''
			},

			// 关闭 Socket
			closeSocket() {
				if (this.socketTask) {
					this.socketTask.close({
						success: () => {
							console.log('✅ WebSocket 关闭成功')
						this.socketTask = null
							this.socketOpen = false
						this.isConnecting = false
					},
						fail: (err) => {
						console.error('❌ WebSocket 关闭失败:', err)
						}
					})
				} else {
					this.socketOpen = false
					this.isConnecting = false
				}
			},

			showError(message) {
				uni.showToast({
					title: message,
					icon: 'none',
					duration: 3000
				})
			}
		}
	}
</script>

<style>
.info {
	padding: 20rpx;
	text-align: center;
}

button {
	margin: 10rpx 0;
	width: 100%;
}

button[disabled] {
	background-color: #ccc !important;
	color: #666;
}

.debug-info {
	background: #f5f5f5;
	padding: 20rpx;
	margin: 20rpx 0;
	border-radius: 10rpx;
	font-size: 24rpx;
	text-align: left;
	word-break: break-all;
}
</style>